import { defineComponent, computed, ref, getCurrentInstance, onActivated, unref } from "vue";
import { BasicTableProps } from "./types";
import { basicProps } from "./props";
import { ignorePropKeys } from "./const";
import { basicEmits } from "./emits";
import XEUtils from "xe-utils";
import type { VxeGridInstance, VxeGridEventProps, GridMethods, TableMethods, TableEditMethods, TableValidatorMethods, VxeGridPropTypes, VxeGridDefines } from "../../../../types/all";
import { VxeGrid } from "../../../../packages/all";
import { extendSlots } from "./helper";
import { gridComponentMethodKeys } from "./methods";
import { omit } from "lodash-es";
import { useTableConfig, loadTable, updateTableConfig } from "@/utils/vxeTableConfig";
import { useDict } from "@/utils/dict";
import { useRoute } from "vue-router";
import useUserStore from "@/store/modules/user";
import { jsonFormat } from "@/utils/common";
import { VxeBasicTable } from "@/components/ElementRender/src/types";
import { isObject, isArray, isString } from "@/utils/is";
import { formFilter, deleteFilter, userColumnWidth, userColumnOrder } from "@/api/system/menuTable/table";
export default defineComponent({
    name: "VxeBasicTable",
    props: basicProps,
    emits: basicEmits,
    async setup(props, { emit, attrs }) {
        const tableElRef = ref<VxeGridInstance>();
        const emitEvents: VxeGridEventProps = {};
        const route = useRoute();

        function getTableAction() {
            const tableAction = unref(tableElRef);
            if (!tableAction) {
                throw new Error("tableAction is null");
            }
            return tableAction;
        }

        onActivated(() => {
            const route = useRoute();
            console.log("组件缓存", route);
        });

        //本地存储的key值
        const key = useUserStore().role?.roleKey + "-" + route.path + "-" + props.tableName;
        // 加载表格配置
        const table = await useTableConfig({ key, role: useUserStore().role, tableName: props.tableName });

        console.log("后端加载表格配置", key, table);
        const tableConfig = jsonFormat(table) as VxeBasicTable;
        console.log("格式化", tableConfig);
        await loadTable(tableConfig, tableElRef);
        console.log("处理表格", tableConfig);

        // 提取表格列字典
        const dictType = ref<any>([]);
        if (tableConfig.columns) {
            XEUtils.arrayEach(tableConfig.columns, (item: any) => {
                if (item.dictType) {
                    if (isString(item.dictType) && item.dictType.indexOf("[") > -1 && item.dictType.indexOf("]") > -1) {
                        item.dictType = JSON.parse(item.dictType);
                    } else if (isString(item.dictType)) {
                        item.dictType = item.dictType.split(",");
                    }
                    dictType.value.push(...item.dictType);
                }
            });
        }

        // 获取字典
        const dict = await useDict(...dictType.value);
        // 字典翻译处理
        function tableDictTransition(t: VxeBasicTable, dictName: any) {
            const a = {};
            XEUtils.objectEach(t, (itemObject, key) => {
                if (isObject(itemObject)) {
                    a[key] = tableDictTransition(itemObject, dictName);
                } else if (isArray(itemObject)) {
                    const arrayData = ref<Array<any>>([]);
                    XEUtils.arrayEach(itemObject, (itemArray) => {
                        if (isObject(itemArray)) {
                            const b = tableDictTransition(itemArray, dictName);
                            arrayData.value.push(b);
                        } else {
                            arrayData.value.push(itemArray);
                        }
                    });
                    a[key] = arrayData.value;
                } else if (key != "dictType" && dictType.value.includes(itemObject)) {
                    const c = dictName + "." + itemObject;
                    a[key] = eval(c);
                } else {
                    a[key] = itemObject;
                }
            });
            return a;
        }

        const gridOptions = ref<any>(tableDictTransition(tableConfig, "dict"));
        // 查询表单处理
        function userFormConfig(formConfig: VxeGridPropTypes.FormConfig) {
            const itemList = ref<Array<any>>([]);
            const filterItemList = ref<Array<any>>([]);
            if (formConfig.filterItems && formConfig.filterItems.length > 0) {
                XEUtils.arrayEach(formConfig.filterItems, (arrayItem: any) => {
                    arrayItem = jsonFormat(arrayItem);
                    filterItemList.value.push(arrayItem);
                });
            }
            if (formConfig.items) {
                XEUtils.arrayEach(formConfig.items, (arrayItem: any) => {
                    arrayItem = jsonFormat(arrayItem);
                    itemList.value.push(arrayItem);
                    // 表单筛选项
                    if (arrayItem.searchHandle && arrayItem["itemRender"] && arrayItem.itemRender["name"] == "$buttonSearchs") {
                        const filter = {
                            ...arrayItem.itemRender.filter,
                            listProps: {
                                data: filterItemList.value.length > 0 ? filterItemList.value : [],
                            },
                            onSelectFilterSearch: (data: any) => {
                                fileterSearch(data);
                            },
                        };
                        if (arrayItem.itemRender["filter"] && !arrayItem.itemRender["filter"]["buttonProps"]) {
                            arrayItem.itemRender.filter.buttonProps = {
                                type: "button",
                                icon: "vxe-icon-add",
                            };
                        }
                        arrayItem.itemRender.filter = filter;
                    }
                });
            }
            formConfig.items = itemList.value.sort(function (prev: any, curr: any) {
                return prev.sortNo - curr.sortNo;
            });
            return formConfig;
        }

        // 表单筛选项处理
        const formFilterDispose = async (form: any) => {
            const formDictType = ref<any>([]);
            const formConfigFilter = ref(userFormConfig(form));
            if (formConfigFilter.value && formConfigFilter.value.items) {
                XEUtils.arrayEach(formConfigFilter.value.items, (item: any) => {
                    if (item.dictType) {
                        if (isString(item.dictType) && item.dictType.indexOf("[") > -1 && item.dictType.indexOf("]") > -1) {
                            item.dictType = JSON.parse(item.dictType);
                        } else if (isString(item.dictType)) {
                            item.dictType = item.dictType.split(",");
                        }
                        formDictType.value.push(...item.dictType);
                    }
                });
            }
            // 获取字典
            const formDict = await useDict(...formDictType.value);
            function tableDictTransitionForm(t: any, dictName: any) {
                const a = {};
                XEUtils.objectEach(t, (itemObject, key) => {
                    if (isObject(itemObject)) {
                        a[key] = tableDictTransitionForm(itemObject, dictName);
                    } else if (key != "dictType" && formDictType.value.includes(itemObject)) {
                        const c = dictName + "." + itemObject;
                        a[key] = eval(c);
                    } else if (isArray(itemObject)) {
                        const arrayData = ref<Array<any>>([]);
                        XEUtils.arrayEach(itemObject, (itemArray) => {
                            if (isObject(itemArray)) {
                                const b = tableDictTransitionForm(itemArray, dictName);
                                arrayData.value.push(b);
                            } else {
                                arrayData.value.push(itemArray);
                            }
                        });
                        a[key] = arrayData.value;
                    } else {
                        a[key] = itemObject;
                    }
                });
                return a;
            }
            return tableDictTransitionForm(formConfigFilter.value, "formDict");
        };
        gridOptions.value["formConfig"] = await formFilterDispose(gridOptions.value["formConfig"]);

        // 添加表单查询项
        const fileterSearch = async ({ data }: any) => {
            const filterSearch = await formFilter(data);
            gridOptions.value["formConfig"] = await formFilterDispose(filterSearch.data["formConfig"]);
        };

        const extendTableMethods = (methodKeys: any) => {
            const funcs: any = {};
            methodKeys.forEach((name: any) => {
                funcs[name] = (...args: any[]) => {
                    const $vxegrid: any = tableElRef.value;
                    if ($vxegrid && $vxegrid[name]) {
                        return $vxegrid[name](...args);
                    }
                };
            });
            return funcs;
        };

        const gridExtendTableMethods = extendTableMethods(gridComponentMethodKeys) as GridMethods & TableMethods & TableEditMethods & TableValidatorMethods;
        basicEmits.forEach((name) => {
            const type = XEUtils.camelCase(`on-${name}`) as keyof VxeGridEventProps;
            emitEvents[type] = (...args: any[]) => emit(name, ...args);
        });

        console.log("配置属性", gridOptions.value);
        /**
         * @description: 二次封装需要的所有属性
         *  1.部分属性需要和全局属性进行合并
         */
        const getBindValues = computed<BasicTableProps>(() => {
            const propsData: BasicTableProps = {
                ...attrs,
                ...props,
                ...gridOptions.value,
            };
            return propsData;
        });
        /**
         * @description: 组件外层class
         */
        const getWrapperClass = computed(() => {
            return [attrs.class];
        });
        /**
         * @description: Table 所有属性
         */
        const getBindGridValues = computed(() => {
            const omitProps = omit(getBindValues.value, ignorePropKeys);
            return {
                ...omitProps,
                ...getBindGridEvent,
                onFormCloseField: formCloseField,
                onResizableChange: resizableChange,
                onCustom: handleCustom,
            };
        });

        /**
         * @description: 重写Vxe-table 方法
         */
        const getBindGridEvent: VxeGridEventProps = {
            ...emitEvents,
        };
        // 表单删除事件
        const formCloseField = async ({ item, params }: any, ...args: any) => {
            const filterSearch = await deleteFilter(item);
            gridOptions.value["formConfig"] = await formFilterDispose(filterSearch.data["formConfig"]);
            emit("form-close-field", { item, params, ...args });
        };
        //列宽调整改变
        const resizableChange = async ({ $rowIndex, column, columnIndex, $columnIndex, $event }: any) => {
            await userColumnWidth(column);
            //更新表格配置数据
            updateTableConfig({ key, role: useUserStore().role, tableName: props.tableName });
            emit("resizable-change", { $rowIndex, column, columnIndex, $columnIndex, $event });
        };
        //列顺序调整
        async function handleCustom({ data, type }: VxeGridDefines.CustomEventParams) {
            if (type === "confirm" || type === "reset") {
                await userColumnOrder(data);
                getTableAction().setColumnIndex(data);
            }
            //更新表格配置数据
            updateTableConfig({ key, role: useUserStore().role, tableName: props.tableName });
            emit("custom", { data, type });
        }

        return {
            getWrapperClass,
            getBindGridValues,
            tableElRef,
            ...gridExtendTableMethods,
            formCloseField,
        };
    },

    render() {
        const { tableClass, tableStyle } = this.$props;
        console.log("999999999999999", this.getBindGridValues);
        return (
            <div class={`${this.getWrapperClass}`}>
                <VxeGrid ref="tableElRef" class={`${tableClass}`} style={tableStyle} {...this.getBindGridValues}>
                    {extendSlots(this.$slots)}
                </VxeGrid>
            </div>
        );
    },
});
